package com.xp.tinyurl.api;

import com.xp.tinyurl.common.utils.BinaryUtil;
import com.xp.tinyurl.model.ShortUrlMap;
import com.xp.tinyurl.service.ShortUrlMapSddlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @Description 短链接跳转路由器（非页面接口）
 * @Author xp
 * @Since 2.0.0
 * @Date 2019/09/24 10:52
 */
@Slf4j
@Controller
public class RouterApi {

    @Autowired
    private ShortUrlMapSddlService shortUrlMapSddlService;

    private static final String NOT_FOUND = "redirect:static/404.html";

    /**
     * 默认url转入404页面
     * @return
     */
    @GetMapping("/")
    public String defaultReq(){
        return NOT_FOUND;
    }

    /**
     * 路由
     * @param uid
     * @return
     */
    @GetMapping("/{uid}")
    public String router(@PathVariable("uid") String uid) {
        if (StringUtils.isEmpty(uid)) {
            return NOT_FOUND;
        }
        long uuid = BinaryUtil.toBase10(uid);
        log.info("short uid is:{}, uuid is : {}",uid, uuid);
        ShortUrlMap shortUrlMap = shortUrlMapSddlService.getLongUrlByShortUrl4Query(uuid);
        if (shortUrlMap == null) {
            log.warn("can't found short url:{},uuid:{}", uid, uuid);
            return NOT_FOUND;
        }
        return "redirect:" + shortUrlMap.getLongUrl();
    }
}
